//
//  SearchViewController.m
//  礼物
//
//  Created by dllo on 15/11/6.
//  Copyright © 2015年 liangsicheng. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchGiftCollectionViewCell.h"
#import "SearchGiftModel.h"
#import "CategoryDetailModel.h"
#import "SearchGiftFourButtonModel.h"
#import "ChannelsModels.h"
#import "EveryDetailViewController.h"

@interface SearchViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong) BaseView *animationView;
@property (nonatomic, strong) BaseCollectionView *collectionView;
@property(nonatomic,strong)NSMutableDictionary *dataDic;
@property (nonatomic, retain) NSMutableArray *searchGiftModelArray;//model数组
@property(nonatomic,strong)NSArray *gifArray;
@property (nonatomic, retain) NSMutableArray *buttonModelArray;//四大按钮数组
@property (nonatomic, assign) NSInteger currentPage;//记录当前page
@property (nonatomic, assign) BOOL isUpLoading;//标记是否为上拉
@property(nonatomic,strong)BaseButton *selectedButton;
@property(nonatomic,assign)BOOL isOpen;
@property(nonatomic,assign)float height;
@property(nonatomic,strong)BaseView *buttonView;
@property(nonatomic,strong)BaseView *line;
@property(nonatomic,copy)NSString *currentUrl;
@property(nonatomic,copy)NSString *name1;
@property(nonatomic,copy)NSString *name2;
@property(nonatomic,copy)NSString *name3;
@property(nonatomic,copy)NSString *name4;
@property(nonatomic,strong)NSMutableArray *nameArray;
@property(nonatomic,copy)NSString *next_url;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.name1 = @"";
     self.name2 = @"";
     self.name3 = @"";
     self.name4 = @"";
    self.nameArray = [NSMutableArray arrayWithObjects:self.name1,self.name2,self.name3,self.name4, nil];

    self.gifArray = [[NSArray alloc] init];
    //导航栏标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 4, 30)];
    titleLabel.text = @"挑选礼物";
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont fontWithName:@"ArialHebrew-Bold" size:20];
    self.navigationItem.titleView = titleLabel;
    //Thonburi-Bold
    self.view.backgroundColor = RGBA(236, 235, 241, 1);
    
    
    self.buttonModelArray = [NSMutableArray array];
    self.searchGiftModelArray = [NSMutableArray array];
    self.dataDic = [NSMutableDictionary dictionary];
    



       UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake((WIDTH - 30) / 2, (HEIGHT - 113) / 2);
    //设置item的行间距
    flowLayout.minimumLineSpacing = 10;
    //设置item的列间距
    flowLayout.minimumInteritemSpacing = 10;
    //设置item的上,左,下,右 边界距离
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    //滑动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    //collectionView
    self.collectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, HEIGHT / 18, WIDTH, HEIGHT - 64 - HEIGHT / 18) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = RGBA(236, 235, 241, 1);
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    
    
    //动画
    self.animationView = [[BaseView alloc] initWithFrame:CGRectMake(0, -self.height+40, WIDTH, self.height)];
    self.animationView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.animationView];
    NSArray *array =  [self.view subviews];
    self.isOpen = NO;
    NSLog(@"array = %@",array);
    self.buttonView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
    self.buttonView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.buttonView];
    for (int i = 0; i<4; i++) {
        BaseButton *button = [BaseButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i*(WIDTH/4),0 , WIDTH/4, 40);
        [self.buttonView addSubview:button];
        button.tag = 1000+i;
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
    }
     self.line = [[BaseView alloc] initWithFrame:CGRectMake(0, 40, WIDTH, 1)];
    self.line.backgroundColor = RGBA(236, 235, 241, 1);
    [self.view addSubview:self.line];
   


        //注册cell
      [self.collectionView registerClass:[SearchGiftCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    self.currentPage = 0;//默认请求下来的数据为第0页
    self.isUpLoading = NO;//默认是下拉状态
    [self addHeaderRefresh];
    
    [self getAFN];
   
}
//设置下拉刷新
- (void)addHeaderRefresh
{
     MJRefreshNormalHeader *header = [MJRefreshNormalHeader   headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
         self.isUpLoading = NO;//标记为下拉
         NSLog(@"下拉");
         self.currentPage = 0;//永远刷新首页,只要下拉,就请求第0页数据
         //重新请求数据
         NSString *url = @"http://api.liwushuo.com/v2/search/item_by_type?limit=20&offset=";
         [self getAFN:self.currentPage andUrl:url];

         NSLog(@"array = %@",self.buttonModelArray);
         if (self.buttonModelArray.count > 0) {
             
             NSArray *array = [self.buttonView subviews];
             for (int  i = 0; i <array.count; i++) {
                 SearchGiftFourButtonModel *buttonModel = [self.buttonModelArray objectAtIndex:i];
                 
                 BaseButton *button =(BaseButton *) [self.buttonView viewWithTag:1000+i];
                 [button setTitle:buttonModel.name forState:UIControlStateNormal];
             }}

    }];

   
    // 马上进入刷新状态
    self.collectionView.header = header;
    [self.collectionView.header beginRefreshing];
}
//设置上拉加载
- (void)addFooterRefresh
{
    NSLog(@"1111111");
        self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.isUpLoading = YES;
         
            [self getAFN:self.next_url];
            NSLog(@"22222");
        }];

    
}

-(void)buttonAction:(BaseButton *)button
{
    CGRect temp = self.animationView.frame;
    SearchGiftFourButtonModel *buttonModel = [self.buttonModelArray objectAtIndex:button.tag - 1000];
    //先判断是否open
    if (self.isOpen) {
       
        temp.origin.y = -self.height;
        //在判断是否点的是同一个
        if (self.selectedButton == button) {
            temp.size.height = self.height ;
            self.isOpen = !self.isOpen;
             self.collectionView.alpha = 1.0;
        }else{
//            若不是  则删除子视图button
            self.selectedButton = button;
        NSArray *subArray =[ self.animationView subviews];
            [self removeSubView:subArray];
           self.height = [self creteButton:buttonModel.channels andValue:button.tag - 1000];
            temp.origin.y = 40;
            temp.size.height = self.height;
            
    }
    }else{
//                [self.viewbringSubviewToFront:self.animationView];
        self.collectionView.alpha = 0.5;
        temp.origin.y = 40;
        if (self.selectedButton == button) {
            temp.size.height = self.height;
            
        }else{
            self.selectedButton = button;
            NSArray *subArray =[ self.animationView subviews];
            [self removeSubView:subArray];
          self.height =  [self creteButton:buttonModel.channels andValue:button.tag-1000];
            temp.size.height = self.height;
}self.isOpen = !self.isOpen;
    }
//    [self.view bringSubviewToFront:self.buttonView];
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
                self.animationView.frame = temp;
        
            } completion:^(BOOL finished) {
        
            }];
        
    
}
//删除子视图
-(void)removeSubView:(NSArray *)array
{
    for (int  i = 0 ; i<array.count; i++) {
        BaseButton *but = [array objectAtIndex:i];
        [but removeFromSuperview];
    }
}
//创建分类button
-(float)creteButton:(NSMutableArray *)array andValue:(NSInteger)value
{
    float heigh = 0.0 ;
    for (int i = 0; i<array.count; i++) {
        BaseButton *button = [BaseButton buttonWithType:UIButtonTypeRoundedRect];
        button.frame = CGRectMake(10 + (((WIDTH - 40) / 3 + 10) * (i % 3)), 10 + (((HEIGHT - 64) / 3 - 40) / 3 + 10) * (i / 3), (WIDTH - 40) / 3, ((HEIGHT - 64) / 3 - 40) / 3);
        button.backgroundColor = [UIColor whiteColor];
        ChannelsModels *channels = [array  objectAtIndex:i];
        [button setTitle:channels.name forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.layer.masksToBounds = YES;//裁剪掉button的边框
        button.layer.cornerRadius = 5;//边框圆角
        button.layer.borderWidth = 1;//边框宽度
        button.layer.borderColor = [UIColor lightGrayColor].CGColor;//边框颜色
        button.tag = (value+1) *10000 + i;
        [button addTarget:self action:@selector(channelButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.animationView addSubview:button];
        if ( i == array.count-1) {
            
            heigh = button.frame.origin.y +button.frame.size.height+10;
            
        }}
    return heigh;
}
-(void)channelButtonAction:(BaseButton *)button
{
    
    NSLog(@"%ld, %ld",button.tag %10000,button.tag / 10000);
    
    SearchGiftFourButtonModel *buttonModel = [self.buttonModelArray objectAtIndex:button.tag / 10000 - 1];
    // button.tag / 10000 表示分类区
    //button.tag %10000 表示所在区的位置
    
    ChannelsModels *channels = [buttonModel.channels objectAtIndex:button.tag %10000];
    BaseButton *btn = (BaseButton *)[self.buttonView viewWithTag:button.tag / 10000 - 1+1000];
    [btn setTitle:channels.name forState:UIControlStateNormal];
        for (int i = 0; i<self.nameArray.count; i++) {
        NSString *name = [self.nameArray objectAtIndex:i];
        NSLog(@"??%ld",button.tag / 10000 - 1);
        if (i ==(button.tag / 10000 - 1)) {
            NSLog(@"??");
            name = channels.key;
            [self.nameArray replaceObjectAtIndex:i withObject:name];
        }
    
    }
    [self.searchGiftModelArray removeAllObjects];
    self.currentUrl = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/item_by_type?target=%@&limit=20&scene=%@&price=%@&personality=%@&offset=",[self.nameArray objectAtIndex:0],[self.nameArray objectAtIndex:1],[self.nameArray objectAtIndex:3],[self.nameArray objectAtIndex:2]];
    NSLog(@"url = %@",self.currentUrl);
    CGRect temp = self.animationView.frame;
    temp.origin.y = -self.height;

    self.collectionView.alpha = 1.0;
    [self getAFN:self.currentUrl];
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        self.animationView.frame = temp;
        
    } completion:^(BOOL finished) {
       
    }];
    self.isOpen = !self.isOpen;
    
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.searchGiftModelArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchGiftCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.layer.masksToBounds = YES;//masksToBounds裁剪掉边框
    cell.layer.cornerRadius = 5;//设置圆角度
    
    SearchGiftModel *searchGiftModel = [self.searchGiftModelArray objectAtIndex:indexPath.row];

     cell.searchGiftModel = searchGiftModel;
        return cell;
}
-(void)getAFN {
    NSString *url_string = @"http://api.liwushuo.com/v2/search/item_filter";
    [AppToolss getAFNetWorkingData:url_string andBlock:^(id data) {
        NSDictionary *dictionary = data;
        NSMutableArray *array = [[dictionary objectForKey:@"data"] objectForKey:@"filters"];
        
        for (NSMutableDictionary *dic in array)
        {
            SearchGiftFourButtonModel *buttonModel = [[SearchGiftFourButtonModel alloc] init];
            buttonModel.id_data = [[dic objectForKey:@"id"] integerValue];
            [buttonModel setValuesForKeysWithDictionary:dic];
            buttonModel.channels = [NSMutableArray array];
            NSArray *channelsArray = [dic objectForKey:@"channels"];
            for (NSDictionary *smallDic in channelsArray) {
                ChannelsModels *channelsModel = [[ChannelsModels alloc] init];
                [channelsModel setValuesForKeysWithDictionary:smallDic];
                channelsModel.item_id = [[smallDic objectForKey:@"id"] intValue];
                [buttonModel.channels addObject:channelsModel];
            }
           
          [self.buttonModelArray addObject:buttonModel];
        }
        [self createButton];
        
        
      } andError:^(id failure) {
    
    
      }];
}
-(void)getAFN:(NSString *)url
{
    if (!self.isUpLoading) {
        [self.searchGiftModelArray removeAllObjects];
    }
    [AppToolss getAFNetWorkingData:url andBlock:^(id data) {
        NSDictionary *dic = data;
        NSArray *items = [[dic objectForKey:@"data"] objectForKey:@"items"];
        NSDictionary *paging = [[dic objectForKey:@"data"] objectForKey:@"paging"];
        id next_url = [paging objectForKey:@"next_url"];
        if (next_url != [NSNull null]) {
            self.next_url = [paging objectForKey:@"next_url"];
        }else{
            self.collectionView.footer = [[MJRefreshFooter alloc] init];
        }
        
        for (NSDictionary *smallDic in items) {
            SearchGiftModel *searchGiftModel = [[SearchGiftModel alloc] init];
            [searchGiftModel setValuesForKeysWithDictionary:smallDic];
            [self.searchGiftModelArray addObject:searchGiftModel];
            
        }
        if (self.searchGiftModelArray.count >= 6) {

            [self addFooterRefresh];
            
        }else{
            
            [self.collectionView.footer resetNoMoreData];
        }
        
        [self.collectionView.footer endRefreshing];
        NSLog(@"333333");
        [self.collectionView reloadData];

    } andError:^(id failure) {
       
        
    }];
}
-(void)getAFN:(NSInteger)page andUrl:(NSString *)url
{
    NSString *Url_string = [NSString stringWithFormat:@"%@%ld",url,page*20];
    if (!self.isUpLoading) {
        [self.searchGiftModelArray removeAllObjects];
    }
    [AppToolss getAFNetWorkingData:Url_string andBlock:^(id data) {
        NSMutableDictionary *dic = data;
        NSMutableArray *array = [[dic objectForKey:@"data"] objectForKey:@"items"];
        NSDictionary *paging = [[dic objectForKey:@"data"] objectForKey:@"paging"];
        self.next_url = [paging objectForKey:@"next_url"];

        for (NSMutableDictionary *dic in array)
        {
            SearchGiftModel *searchGiftModel = [[SearchGiftModel alloc] init];
            [searchGiftModel setValuesForKeysWithDictionary:dic];
            searchGiftModel.descriptions = [dic objectForKey:@"description"];
            
            [self.searchGiftModelArray addObject:searchGiftModel];
            [self.collectionView.header endRefreshing];
            [self.collectionView reloadData];
          
        }

        
    } andError:^(id failure) {
        
//        UIAlertController *arltC = [UIAlertController alertControllerWithTitle:@"刷新失败" message:@"请重试" preferredStyle:UIAlertControllerStyleAlert];
        
    
        
        [self.collectionView.header endRefreshing];

    }];
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CategoryDetailModel *categoryDetailModel = [self.searchGiftModelArray objectAtIndex:indexPath.row];
    EveryDetailViewController *everyDetailVC = [[EveryDetailViewController alloc] init];
    everyDetailVC.categoryDetail = categoryDetailModel;
    [self.navigationController pushViewController:everyDetailVC animated:YES];
}
-(void)createButton
{
    NSLog(@"count = %ld",self.buttonModelArray.count);
    for (int i = 0; i<self.buttonModelArray.count; i++) {
        BaseButton *button =(BaseButton *) [self.buttonView viewWithTag:1000+i];
        SearchGiftFourButtonModel *buttonModel = [self.buttonModelArray objectAtIndex:i];
        [button setTitle:buttonModel.name forState:UIControlStateNormal];
        [button setTitle:buttonModel.name forState:UIControlStateHighlighted];
        
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
